package com.appkubes.mall.restful.application.wx.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.appkubes.common.utils.net.HttpClientUtils;
import com.appkubes.mall.restful.application.wx.model.CreditModel;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class CreditService {

    private static String ADDORDER_URL = "http://service-fintech-restful.demo.appkubes.com/order/add";

    private static String CANCEL_URL = "http://service-fintech-restful.demo.appkubes.com/order/cancel";

    public JSONObject addZuLinOrder(CreditModel model) throws Exception {
        JSONObject object = new JSONObject();
        object.put("creditAmount", model.getCreditAmount());
        object.put("creditIncreaseAmount", model.getCreditIncreaseAmount());
        object.put("fistPayAmount", model.getFistPayAmount());
        object.put("goodsAmount", model.getGoodsAmount());
        object.put("goodsTitle", model.getGoodsTitle());
        object.put("orderKey", model.getOrderKey());
        object.put("periodsCode", model.getPeriodsCode());
        object.put("rentAmount", model.getRentAmount());
        object.put("rentType", model.getRentType());
        object.put("userKey", model.getUserKey());
        object.put("interestRate", 1.00);
        Response response = HttpClientUtils.post(ADDORDER_URL, object.toJSONString());
        String str = response.body().string();
        if (!StringUtils.isEmpty(str)) {
            JSONObject jsonObject = JSON.parseObject(str);
            if (jsonObject.getInteger("sms") != 200) {
                throw new Exception("租赁下单失败");
            }
            return jsonObject;
        }
        throw new Exception("租赁下单失败");
    }

    public JSONObject cancelZuLinOrder(CreditModel creditModel) throws Exception {
        Map<String, String> map = new HashMap<>();
        map.put("orderKey", creditModel.getOrderKey());
        map.put("userKey", creditModel.getUserKey());

        System.out.println(map);
        String str = HttpClientUtils.postForBody(CANCEL_URL, map);
        if (!StringUtils.isEmpty(str)) {
            JSONObject jsonObject = JSON.parseObject(str);
            if (jsonObject.getInteger("sms") != 200) {
                throw new Exception("租赁订单取消失败");
            }
            return jsonObject;
        }
        throw new Exception("租赁订单取消失败");
    }
}
